package com.erp.erp_ui.Purchase;

import com.alibaba.fastjson.JSONObject;
import com.erp.enums.OperationStatusEnum;
import com.erp.erp_entitys.Blueprint.BlueprintFileEntity;
import com.erp.erp_entitys.Customer2.Customer2Entity;
import com.erp.erp_entitys.Purchase.*;
import com.erp.erp_entitys.Purchase.req.PurchaseOrderRestockReq;
import com.erp.erp_entitys.Purchase.req.PurchaseProductIntegrationReq;
import com.erp.erp_entitys.Purchase.req.purchaseSampleStatisticsReq;
import com.erp.erp_entitys.Purchase.res.PurchaseDataVo;
import com.erp.erp_entitys.Purchase.res.PurchaseOrderRestockRes;
import com.erp.erp_entitys.Purchase.res.PurchaseProductIntegrationRes;
import com.erp.erp_entitys.Purchase.res.purchaseSampleStatisticsRes;
import com.erp.erp_entitys.User.UserEntity;
import com.erp.erp_entitys.business.entity.ExportContractEntity;
import com.erp.erp_servers.Customer2.ICustomer2Service;
import com.erp.erp_servers.Ftp.IFtpService;
import com.erp.erp_servers.Purchase.*;
import com.erp.erp_ui.Message.req.EditMessageReq;
import com.erp.erp_ui.Message.service.MessageAllService;
import com.erp.erp_ui.Purchase.Service.PurchaseAllService;
import com.erp.erp_ui.Purchase.Service.PurchaseFeedbackAllService;
import com.erp.erp_ui.base.Base;
import com.erp.erp_ui.warehouse.enums.DataIsValidEnum;
import com.erp.utils.R;
import com.erp.utils.ResultStatusEnum;
import com.erp.utils.StringUtil;
import com.erp.vo.SelectVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

@Controller
@RequestMapping(value = "purchase")
@Api( tags = "采购")
public class PurchaseControl extends Base {
    @Autowired
    private IPurchaseService purchaseService;
    @Autowired
    private IPurchaseProductService purchaseProductService;
    @Autowired
    private IPurchaseFileService purchaseFileService;
    @Autowired
    private IFtpService ftpService;
    @Autowired
    private IPurchaseLogService purchaseLogService;
    @Autowired
    private IPurchaseFeedbackService purchaseFeedbackService;
    @Autowired
    private PurchaseFeedbackAllService purchaseFeedbackAllService;

    @Autowired
    ICustomer2Service customerService;
    /**
     * 消息接口
     */
    @Autowired
    MessageAllService messageAllService;
    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(PurchaseControl.class);

    @Autowired
    PurchaseAllService purchaseAllService;


    /**
     * 新增采购
     * @param purchase
     * @return 操作记录数
     */
    @RequestMapping(value = "insert" ,method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增采购", notes = "新增采购", httpMethod = "POST")
    public R<Integer> insert(@RequestBody Purchase purchase){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                if(StringUtils.isEmpty(purchase.getPurchaseOrderNo())){
                    return  R.buildError(ResultStatusEnum.NOT_EMPTY);
                }
                boolean isExist = purchaseService.isExist(purchase.getPurchaseOrderNo());
                if(isExist){
                    return  R.buildError(ResultStatusEnum.BILL_NO_REPEAT);
                }
                UserEntity user = (UserEntity )cacheUser;
                purchase.setExecutorCode(user.getCode());
                String upUser = user.getName()+":"+user.getCode();
                purchase.setUpUser(upUser);
                Integer upType = 1;
                purchase.setUpType(upType);
                Date nowDate = new Date(System.currentTimeMillis());
                purchase.setUpTime(nowDate);
                purchase.setBoxStatus("1");
                purchase.setValid(1);
                purchase.setCreateTime(nowDate);
                int num = purchaseService.insert(purchase);
                PurchaseLog purchaseLog = new PurchaseLog(purchase.getId(), upType, 1, upUser, nowDate, "单号："+purchase.getPurchaseOrderNo());
                int logNum = purchaseLogService.insert(purchaseLog);
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (Exception e){
            e.printStackTrace();
            return  R.buildError(ResultStatusEnum.ERROR);
        }
    }
    
    /**
     * 按id查询采购
     * @param id
     * @return 采购实体
     */
    @RequestMapping(value = "selectByKey/{id}")
    @ResponseBody
    @ApiOperation(value = "按id查询采购",notes = "按id查询采购",httpMethod = "POST")
    public R<Purchase> selectByKey(@PathVariable("id") Integer id){
        try {
            if (id==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            Purchase purchase = purchaseService.selectByPrimaryKey(id);
            if (purchase==null){
                return R.buildError(ResultStatusEnum.NOT_FOUND);
            }
            return R.build(purchase);
        } catch (NumberFormatException e1){
            e1.printStackTrace();
            return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
        } catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按id更新采购
     * 部分字段
     * @param purchase
     * @return 操作记录数
     */
    @RequestMapping(value = "update")
    @ResponseBody
    @ApiOperation(value = "按id更新采购", notes = "按id更新采购", httpMethod = "POST")
    public R<Integer> update(@RequestBody Purchase purchase){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                //1.单号唯一性校验
                boolean billNoCheckFlag = purchase.getPurchaseOrderNo().equals(purchase.getNewBillNo());
                if(!billNoCheckFlag){
                    //单号做唯一校验
                    boolean billNoFlag = checkRepeatBillNo(purchase.getPurchaseOrderNo());
                    if(!billNoFlag){
                        return R.buildError(ResultStatusEnum.BILL_NO_REPEAT);
                    }
                }
                UserEntity user = (UserEntity )cacheUser;
                String upUser = user.getName()+":"+user.getCode();
                Integer upType = 3;
                purchase.setUpType(upType);
                purchase.setUpUser(upUser);
                Date nowDate = new Date(System.currentTimeMillis());
                purchase.setUpTime(nowDate);
                purchase.setEditTime(nowDate);
                int num = purchaseService.updateByPrimaryKey(purchase);
                PurchaseLog purchaseLog = new PurchaseLog(purchase.getId(), upType, 1, upUser, nowDate, "单号："+purchase.getPurchaseOrderNo());
                int logNum = purchaseLogService.insert(purchaseLog);
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 校验单号是否存在
     * @param billNo 单号
     * @return true:不重复 false:重复
     */
    private boolean checkRepeatBillNo(String billNo){
        Purchase req = new Purchase();
        req.setPurchaseOrderNo(billNo);
        List<Purchase> list = purchaseService.queryAll(req);
        if(CollectionUtils.isEmpty(list)){
            return true;
        }
        return false;
    }

    /**
     * 按主键id删除采购
     * @param id
     * @return 操作记录数
     */
    @RequestMapping(value = "delete/{id}")
    @ResponseBody
    @ApiOperation(value = "按id删除采购", notes = "按id删除采购", httpMethod = "POST")
    public R<Integer> delete(@PathVariable("id") Integer id){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                UserEntity user = (UserEntity )cacheUser;
                Purchase purchase = purchaseService.selectByPrimaryKey(id);
                int num = 0;
                if(purchase!=null){
                    String upUser = user.getName()+":"+user.getCode();
                    Integer upType = 2;
                    num = purchaseService.deleteByPrimaryKey(id, upType, upUser);
                    Date nowDate = new Date(System.currentTimeMillis());
                    PurchaseLog purchaseLog = new PurchaseLog(id, upType, 1, upUser, nowDate, "单号："+purchase.getPurchaseOrderNo());
                    int logNum = purchaseLogService.insert(purchaseLog);
                }
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (Exception e){
            e.printStackTrace();
            return  R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 新增采购产品记录
     * @param purchaseProduct
     * @return 操作记录数
     */
    @RequestMapping(value = "insertProduct" ,method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增采购产品", notes = "新增采购产品", httpMethod = "POST")
    public R<Integer> insertProduct(@RequestBody PurchaseProduct purchaseProduct){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                int num = purchaseProductService.insertSelective(purchaseProduct);
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (DataIntegrityViolationException e1){
            e1.printStackTrace();
            return R.buildError(ResultStatusEnum.DATA_ERROR);
        }catch (Exception e){
            e.printStackTrace();
            return  R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按id查询采购产品记录
     * @param id
     * @return 采购产品
     */
    @RequestMapping(value = "selectProductByKey/{id}")
    @ResponseBody
    @ApiOperation(value = "按id查询采购产品",notes = "按id查询采购产品",httpMethod = "POST")
    public R<PurchaseProduct> selectProductByKey(@PathVariable("id") Integer id){
        try {
            if (id==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            PurchaseProduct purchaseProduct = purchaseProductService.selectByPrimaryKey(id);
            if (purchaseProduct==null){
                return R.buildError(ResultStatusEnum.NOT_FOUND);
            }
            return R.build(purchaseProduct);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按id更新采购-产品
     * 部分字段
     * @param purchaseProduct
     * @return 操作记录数
     */
    @RequestMapping(value = "updateProduct")
    @ResponseBody
    @ApiOperation(value = "按id更新采购产品", notes = "按id更新采购产品", httpMethod = "POST")
    public R<Integer> updateProduct(@RequestBody PurchaseProduct purchaseProduct){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                int num = purchaseProductService.updateByPrimaryKeySelective(purchaseProduct);
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按主键id删除采购-产品
     * @param id
     * @return 操作记录数
     */
    @RequestMapping(value = "deleteProduct/{id}")
    @ResponseBody
    @ApiOperation(value = "按id删除采购产品", notes = "按id删除采购产品", httpMethod = "POST")
    public R<Integer> deleteProduct(@PathVariable("id") Integer id){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                UserEntity user = (UserEntity )cacheUser;
                PurchaseProduct purchaseProduct = purchaseProductService.selectByPrimaryKey(id);
                int num = 0;
                if(purchaseProduct!=null){
                    num = purchaseProductService.deleteByPrimaryKey(id);
                }
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (Exception e){
            e.printStackTrace();
            return  R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 新增采购附件
     * @param inquiryFile
     * @return 操作记录数
     */
    @RequestMapping(value = "insertFile" ,method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增采购附件", notes = "新增采购附件", httpMethod = "POST")
    public R<Integer> insertFile(@RequestBody PurchaseFile inquiryFile){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                int num = purchaseFileService.insertSelective(inquiryFile);
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (DataIntegrityViolationException e1){
            e1.printStackTrace();
            return R.buildError(ResultStatusEnum.DATA_ERROR);
        }catch (Exception e){
            e.printStackTrace();
            return  R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按id查询采购附件
     * @param id
     * @return 采购附件实体
     */
    @RequestMapping(value = "selectFileByKey/{id}")
    @ResponseBody
    @ApiOperation(value = "按id查询采购附件",notes = "按id查询采购附件",httpMethod = "POST")
    public R<PurchaseFile> selectFileByKey(@PathVariable("id") Integer id){
        try {
            if (id==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            PurchaseFile inquiryFile = purchaseFileService.selectByPrimaryKey(id);
            if (inquiryFile==null){
                return R.buildError(ResultStatusEnum.NOT_FOUND);
            }
            return R.build(inquiryFile);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按id更新采购-附件
     * 部分字段
     * @param inquiryFile
     * @return 操作记录数
     */
    @RequestMapping(value = "updateFile")
    @ResponseBody
    @ApiOperation(value = "按id更新采购", notes = "按id更新采购产品记录", httpMethod = "POST")
    public R<Integer> updateFile(@RequestBody PurchaseFile inquiryFile){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                int num = purchaseFileService.updateByPrimaryKeySelective(inquiryFile);
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按主键id删除采购-附件
     * @param id
     * @return 操作记录数
     */
    @RequestMapping(value = "deleteFile/{id}")
    @ResponseBody
    @ApiOperation(value = "按id删除采购附件", notes = "按id删除采购附件", httpMethod = "POST")
    public R<Integer> deleteFile(@PathVariable("id") Integer id){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                UserEntity user = (UserEntity )cacheUser;
                PurchaseFile inquiryFile = purchaseFileService.selectByPrimaryKey(id);
                int num = 0;
                if(inquiryFile!=null){
                    num = purchaseFileService.deleteByPrimaryKey(id);
                }
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (Exception e){
            e.printStackTrace();
            return  R.buildError(ResultStatusEnum.ERROR);
        }
    }



    /**
     * 根据puId查询采购 -产品
     * @param puId
     * @return 采购-产品
     */
    @RequestMapping(value = "selectProductByPuId/{puId}",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "根据puId查询采购产品记录", notes ="根据puId查询采购产品记录", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name="puId",value = "采购id"),
    })
    public R<List<PurchaseProduct>> selectProductByPuId(@PathVariable("puId") Integer puId){
        try {
            if (puId==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            List<PurchaseProduct> list = purchaseProductService.selectProductByPuId(puId);
            for (int i = 0; i < list.size(); i++) {
                PurchaseProduct pro = list.get(i);
                BigDecimal priceSubtotal = BigDecimal.ZERO;
                BigDecimal costPrice = pro.getCostPrice();
                BigDecimal price = BigDecimal.ZERO;
                BigDecimal otherPrice = pro.getOtherPrice();
                BigDecimal amount = pro.getAmount();
                if(amount.compareTo(BigDecimal.ZERO)==1){
                    priceSubtotal = costPrice;
                }else{
                    priceSubtotal = costPrice;
                    BigDecimal temp = otherPrice.divide(amount,BigDecimal.ROUND_HALF_UP);
                    priceSubtotal = priceSubtotal.add(temp);
                }
                priceSubtotal = priceSubtotal.multiply(amount);
                pro.setPriceSubtotal(priceSubtotal.setScale(6,BigDecimal.ROUND_HALF_UP));
                list.set(i, pro);
            }
            if (list==null){
                return R.buildError(ResultStatusEnum.SELECT_LIST_ISNULL_ERROR);
            }
            return R.build(list);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }

    }

    /**
     * 根据puId查询采购-附件
     * @param puId
     * @return 采购-附件
     */
    @RequestMapping(value = "selectFileByPuId/{puId}",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "根据puId查询采购附件", notes ="根据puId查询采购附件", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name="puId",value = "采购id"),
    })
    public R<List<PurchaseFile>> selectFileByPuId(@PathVariable("puId") Integer puId){
        try {
            if (puId==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            List<PurchaseFile> list = purchaseFileService.selectFileByPuId(puId);
            if (list==null){
                return R.buildError(ResultStatusEnum.SELECT_LIST_ISNULL_ERROR);
            }
            return R.build(list);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 根据puId查询采购-附件
     * @param puId
     * @return 采购-附件
     */
    @RequestMapping(value = "selectLogByPuId/{puId}",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "根据puId查询采购日志", notes ="根据puId查询采购日志", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name="puId",value = "采购id"),
    })
    public R<List<PurchaseLog>> selectLogByPuId(@PathVariable("puId") Integer puId){
        try {
            if (puId==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            List<PurchaseLog> list = purchaseLogService.selectLogByPuId(puId);
            if (list==null){
                return R.buildError(ResultStatusEnum.SELECT_LIST_ISNULL_ERROR);
            }
            return R.build(list);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }

    }

    /**
     * 按条件采购
     * @param vo
     * @return 采购集合
     */
    @RequestMapping(value = "selectPurchaseList",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "根据条件查询采购", notes ="根据条件查询采购", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name="boxStatus",value = "单据类型"),
            @ApiImplicitParam(name="numberLike",value = "单据信息"),
            @ApiImplicitParam(name="executor",value = "所属操作员"),
            @ApiImplicitParam(name="salesman",value = "所属业务员"),
            @ApiImplicitParam(name="startInquiryTime",value = "询价开始日期"),
            @ApiImplicitParam(name="endInquiryTime",value = "询价结束日期"),
            @ApiImplicitParam(name="startCreateTime",value = "创建开始时间"),
            @ApiImplicitParam(name="endCreateTime",value = "创建结束时间"),
            @ApiImplicitParam(name="pageNum",value = "当前页"),
            @ApiImplicitParam(name="pageSize",value = "页内条数")
    })
    public R selectPurchaseList(@RequestBody PurchaseVo vo){
        try {
            if (vo ==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            Date date = new Date(System.currentTimeMillis());
            if (vo.getStartDeliverTime()!=null){
                if (vo.getEndDeliverTime()==null){
                    vo.setEndDeliverTime(date);
                }
            }
            if (vo.getStartCreateTime()!=null){
                if (vo.getEndCreateTime()==null){
                    vo.setEndCreateTime(date);
                }
            }
            PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
            PageInfo<PurchaseDataVo> pageInfo = purchaseService.selectPurchaseList(vo);
            if(CollectionUtils.isEmpty(pageInfo.getList())){
                return  R.buildError(ResultStatusEnum.SELECT_LIST_ISNULL_ERROR);
            }
            return R.build(0,"", pageInfo.getTotal(), pageInfo.getList());
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 判断角色是否包含 研发助理 研发主管
     * false:包含
     * true:不包含
     */
    @RequestMapping("/isNotResearchAndDevelopment")
    @ResponseBody
    public R isNotResearchAndDevelopment(){
        UserEntity user = (UserEntity) this.getBean("user");
        if (user.getRoles().contains("YFZG011") || user.getRoles().contains("YFZL012")){
            return R.build(false);
        }else {
            return R.build(true);
        }

    }

    /**
     * 按id更新审核状态
     * 部分字段
     * @param vo
     * @return 操作记录数
     */
    @RequestMapping(value = "updateBoxStatusByKey")
    @ResponseBody
    @ApiOperation(value = "按id更新审核状态", notes = "按id更新审核状态", httpMethod = "POST")
    public R<Integer> updateBoxStatusByKey(@RequestBody PurchaseVo vo){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                if (null== vo || null == vo.getId() || null == vo.getBoxStatus()){
                    return  R.buildError(ResultStatusEnum.PARAMETER_ERROR);
                }
                UserEntity user = (UserEntity )cacheUser;
                Purchase purchase = purchaseService.selectByPrimaryKey(vo.getId());
                double oldBoxStatus = Double.parseDouble(purchase.getBoxStatus());
                double newBoxStatus = Double.parseDouble(vo.getBoxStatus());
                String newBoxStatusStr = StringUtil.convertDoubleToString(newBoxStatus);
                if(oldBoxStatus<4 || oldBoxStatus == OperationStatusEnum.TERMINATION_BOX.getId()){
                    PurchaseProcessEntity pp = new PurchaseProcessEntity();
                    pp.setPurchaseNo(purchase.getPurchaseOrderNo());
                    pp.setSTATUS(newBoxStatusStr);
                    if(user.getCode().equals("RKB037")){//于
                        pp.setIsend(0);
                    }else if(user.getDepartmentCode().equals("YFB")){//技术部的 袁豫周
                        pp.setTjr(user.getCode());
                        pp.setSpr("RKB012");
                        if (user.getMsn().equals("是")){
                            if(newBoxStatus>oldBoxStatus){
                                pp.setIsend(0);
                            }
                        }

                    }else{
                        pp.setTjr(user.getCode());
                        pp.setSpr("RKB037");
                        pp.setIsend(0);
                    }
                    purchaseService.insertProcess(pp);

                    //提交审批 通知消息
                    if (newBoxStatus==2 || newBoxStatus==2.1){
                        addMessage(purchase,user);
                    }

                }
                vo.setBoxStatus(newBoxStatusStr);//重新设置vo单据类型
                int num = purchaseService.updateBoxStatusByKey(vo);
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 新增消息
     * 提交审批 添加到消息表，
     * 普通员工提交审批后通知给于雅静，于雅静通过之后通知给许成龙
     * 李启成提交的单据通知给胡婉琪
     */
    public void addMessage(Purchase record, UserEntity user) throws ParseException {
        String receiverCode="";
        if (user.getMsn().equals("否") && !user.getCode().equals("RKB098")){//普通人
            if (user.getDepartmentCode().equals("YFB")){//技术部
                receiverCode="RKB012";//通知给袁豫周
            }else {
                receiverCode="RKB037";//通知给于雅静
            }
        }else if (user.getMsn().equals("是") && !user.getCode().equals("RKB098")){//管理层
            if (!user.getDepartmentCode().equals("YFB")) {//不属于技术部
                receiverCode="RKB007";//通知给许成龙
            }
        }else if (user.getCode().equals("RKB098")){//李启成
            receiverCode="RKB010";//通知给胡婉琪
        }

        EditMessageReq req=new EditMessageReq();
        req.setTheme("采购待审批");
        req.setReceiverCode(receiverCode);
        req.setMessageType(4);
        req.setContent("订单号为："+record.getPurchaseOrderNo());
        messageAllService.editMessage(req,user.getName(),user.getCode());
    }

    /**
     * 按供应商code查询采购
     * @param code
     * @return 采购实体
     */
    @RequestMapping(value = "selectSupplierByCode/{code}")
    @ResponseBody
    @ApiOperation(value = "按id查询采购",notes = "按id查询采购",httpMethod = "POST")
    public R<Customer2Entity> selectSupplierByCode(@PathVariable("code") String code){
        try {
            if (code==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            Customer2Entity customer2 = purchaseService.selectCustomer2ByCode(code);
            if (customer2==null){
                return R.buildError(ResultStatusEnum.SELECT_LIST_ISNULL_ERROR);
            }
            return R.build(customer2);
        } catch (NumberFormatException e1){
            e1.printStackTrace();
            return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
        } catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }


    /**
     * 分页查询 外销合同列表
     * @param vo 查询参数
     * @return
     */
    @RequestMapping(value = "selectExportByPage",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "按条件查询外销合同", notes ="按条件查询外销合同", httpMethod = "GET")
    public R selectExportByPage(ExportVo vo){
        try {
            if (vo==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            Date date = new Date(System.currentTimeMillis());
            if (vo.getStartDeliverTime()!=null){
                if (vo.getEndDeliverTime()==null){
                    vo.setEndDeliverTime(date);
                }
            }
            PageInfo<ExportVo> pageInfo = purchaseProductService.selectExportByList(vo);
            if (pageInfo==null){
                return R.buildError(ResultStatusEnum.SELECT_LIST_ISNULL_ERROR);
            }
            return R.build(0,"", pageInfo.getTotal(), pageInfo.getList());
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按exIds查询外销合同-产品列表
     * @param
     * @return
     */
    @RequestMapping(value = "selectExportProductByExIds",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "按exIds查询外销合同-产品列表", notes ="按exIds查询外销合同-产品列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name="exIds",value = "外销合同ids"),
    })
    public R selectExportProductByExIds(@RequestBody Map<String,Object> map){
        try {
            Object exIdsObj = map.get("exIds");

            List<Integer> result = new ArrayList<>();
            if (exIdsObj instanceof ArrayList<?>) {
                for (Object o : (List<?>) exIdsObj) {
                    result.add(Integer.class.cast(o));
                }
            }

            if(null == result || result.size()==0){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            PageInfo<PurchaseProduct> pageInfo = purchaseProductService.selectExportProductByExIds(result);
            return R.build(0,"", pageInfo.getTotal(), pageInfo.getList());
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按产品编码和规格编码查询 产品规格信息列表
     * @param
     * @return
     */
    @RequestMapping(value = "selectExportProductPartByCode",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "按产品编码和规格编码查询 产品规格信息列表", notes ="按产品编码和规格编码查询 产品规格信息列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name="productCode",value = "产品编码"),
            @ApiImplicitParam(name="productGgCode",value = "规格编码"),
    })
    public R selectExportProductPartByCode(@RequestBody  Map<String,Object> map){
        try {
            String productCode = map.get("productCode").toString();
            String productGgCode = map.get("productGgCode").toString();
            if(StringUtils.isEmpty(productCode)||StringUtils.isEmpty(productGgCode)){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            PageInfo<PurchaseProduct> pageInfo = purchaseProductService.selectExportProductPartByCode(productCode,productGgCode);
            return R.build(0,"", pageInfo.getTotal(), pageInfo.getList());
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 分页查询 任务（备货）列表
     * @param vo 查询参数
     * @return
     */
    @RequestMapping(value = "selectTaskByPage",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "按条件查询任务（备货）", notes ="按条件查询任务（备货）", httpMethod = "GET")
    public R selectTaskByPage(TaskVo vo){
        try {
            if (vo==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            Date date = new Date(System.currentTimeMillis());
            if (vo.getStartDeliverTime()!=null){
                if (vo.getEndDeliverTime()==null){
                    vo.setEndDeliverTime(date);
                }
            }
            PageInfo<TaskVo> pageInfo = purchaseProductService.selectTaskByList(vo);
            if (pageInfo==null){
                return R.buildError(ResultStatusEnum.SELECT_LIST_ISNULL_ERROR);
            }
            return R.build(0,"", pageInfo.getTotal(), pageInfo.getList());
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按taskIds查询任务（备货）-产品列表
     * @param
     * @return
     */
    @RequestMapping(value = "selectTaskProductByTaskIds",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "按taskIds查询任务（备货）-产品列表", notes ="按taskIds查询任务（备货）-产品列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name="taskIds",value = "外销合同ids"),
    })
    public R selectTaskProductByTaskIds(@RequestBody Map<String,Object> map){
        try {
            Object taskIdsObj = map.get("taskIds");

            List<Integer> result = new ArrayList<>();
            if (taskIdsObj instanceof ArrayList<?>) {
                for (Object o : (List<?>) taskIdsObj) {
                    result.add(Integer.class.cast(o));
                }
            }

            if(null == result || result.size()==0){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            PageInfo<PurchaseProduct> pageInfo = purchaseProductService.selectTaskProductByTaskIds(result);
            return R.build(0,"", pageInfo.getTotal(), pageInfo.getList());
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }


    /**
     * 按exportIds查询-外销配件列表
     * @param
     * @return
     */
    @RequestMapping(value = "selectExportPartByExportIds",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "按exportIds查询-外销配件列表", notes ="按exportIds查询-外销配件列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name="exportIds",value = "外销合同ids"),
    })
    public R selectExportPartByExportIds(@RequestBody Map<String,Object> map){
        try {
            Object exportIdsObj = map.get("exportIds");

            List<Integer> result = new ArrayList<>();
            if (exportIdsObj instanceof ArrayList<?>) {
                for (Object o : (List<?>) exportIdsObj) {
                    result.add(Integer.class.cast(o));
                }
            }

            if(null == result || result.size()==0){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            PageInfo<PurchaseProduct> pageInfo = purchaseProductService.selectExportPartByExportIds(result);
            return R.build(0,"", pageInfo.getTotal(), pageInfo.getList());
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按taskIds查询任务（备货）-配件列表
     * @param
     * @return
     */
    @RequestMapping(value = "selectTaskPartByTaskIds",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "按taskIds查询任务（备货）-配件列表", notes ="按taskIds查询任务（备货）-配件列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name="taskIds",value = "备货ids"),
    })
    public R selectTaskPartByTaskIds(@RequestBody Map<String,Object> map){
        try {
            Object taskIdsObj = map.get("taskIds");

            List<Integer> result = new ArrayList<>();
            if (taskIdsObj instanceof ArrayList<?>) {
                for (Object o : (List<?>) taskIdsObj) {
                    result.add(Integer.class.cast(o));
                }
            }

            if(null == result || result.size()==0){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            PageInfo<PurchaseProduct> pageInfo = purchaseProductService.selectTaskPartByTaskIds(result);
            return R.build(0,"", pageInfo.getTotal(), pageInfo.getList());
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 根据puId查询采购-附件
     * @param map
     * @return 采购-附件
     */
    @RequestMapping(value = "selectBlueprintFileByCode",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "根据puId查询采购附件", notes ="根据puId查询采购附件", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name="puId",value = "采购id"),
    })
    public R selectBlueprintFileByCode(@RequestBody Map<String,String> map){
        try {
            if (map==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            List<BlueprintFileEntity> list = purchaseFileService.selectBlueprintFileByCode(map);
            if (list==null){
                return R.buildError(ResultStatusEnum.SELECT_LIST_ISNULL_ERROR);
            }
            return R.build(list);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }

    }

    /**
     * 按采购单号查询采购全部信息
     * @param purchaseOrderNo 采购单号
     * @return
     */
    @RequestMapping(value = "selectByNo")
    @ResponseBody
    @ApiOperation(value = "按采购单号查询采购全部信息",notes = "按采购单号查询采购全部信息",httpMethod = "POST")
    public R<Purchase> selectByNo(String purchaseOrderNo){
        try {
            if (purchaseOrderNo==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            Purchase purchase = purchaseService.selectByNo(purchaseOrderNo);
            if (purchase==null){
                return R.buildError(ResultStatusEnum.NOT_FOUND);
            }
            return R.build(purchase);
        } catch (NumberFormatException e1){
            e1.printStackTrace();
            return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
        } catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按采购id上传logo和公章图片 查询图片路径
     * @return 图片路径
     */
    @RequestMapping(value = "selectImgUrlById/{id}")
    @ResponseBody
    @ApiOperation(value = "按采购id查询图片路径",notes = "按采购id查询图片路径",httpMethod = "POST")
    public R selectImgUrlById(@PathVariable("id") Integer id){
        try {
            if (id==null){
                return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
            }
            ImgUrl imgUrl = purchaseService.selectImgUrlById(id);
            if (imgUrl==null){
                return R.buildError(ResultStatusEnum.SELECT_LIST_ISNULL_ERROR);
            }
            if(StringUtils.isNotEmpty(imgUrl.getClogo())){
                ftpService.ftpUpload(imgUrl.getClogo());
            }
            if(StringUtils.isNotEmpty(imgUrl.getElogo())){
                ftpService.ftpUpload(imgUrl.getElogo());
            }
            if(StringUtils.isNotEmpty(imgUrl.getSealImg())){
                ftpService.ftpUpload(imgUrl.getSealImg());
            }
            return R.build(imgUrl);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按id更新采购附件
     * 部分字段
     * @param purchase
     * @return 操作记录数
     */
    @RequestMapping(value = "updatePurchaseFile/{id}")
    @ResponseBody
    @ApiOperation(value = "按id更新采购", notes = "按id更新采购", httpMethod = "POST")
    public R<Integer> updatePurchaseFile(@PathVariable("id") Integer id, @RequestBody Purchase purchase){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                UserEntity user = (UserEntity )cacheUser;
                if(null == id || CollectionUtils.isEmpty(purchase.getFileList())){
                    return R.buildError(ResultStatusEnum.PARAMETER_ERROR);
                }
                int num = purchaseService.updatePurchaseFile(id, user.getCode(), purchase.getFileList());
                return R.build(num);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 根据采购单号获取名称中包含fileName的信息的附件
     * @param purchaseOrderNo
     * @return
     */
    @RequestMapping(value = "import/getFileByPurchaseOrderNo")
    @ResponseBody
    public R<List<PurchaseFile>> getFileByPurchaseOrderNo(String purchaseOrderNo ){
        try {
            List<PurchaseFile> fileByPurchaseOrderNo = purchaseService.getFileByPurchaseOrderNo(purchaseOrderNo, "RKB采购订单");
            return R.build(fileByPurchaseOrderNo);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }


    /**
     * 添加采购的反馈
     * @param purchaseFeedbackList
     * @return
     */
    @RequestMapping("addFeedbackDate")
    @ResponseBody
    public R addFeedbackDate(@RequestBody List<PurchaseFeedback> purchaseFeedbackList){
        try {
            R r=purchaseFeedbackAllService.addPurchaseFeedback(purchaseFeedbackList);
            return R.build(r);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 根据条件查询反馈信息
     * @param purchaseFeedback
     * @return
     */
    @RequestMapping("getFeedbackDateByParam")
    @ResponseBody
    public R getFeedbackDateByParam(PurchaseFeedback purchaseFeedback){
        try {
            List<QueryPurchaseFeedbackVO> data=purchaseFeedbackService.getFeedbackDateByParam(purchaseFeedback);
            return R.build(data);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 保存采购审批信息
     * @param purchaseProcessEntity
     * @return
     */
    @RequestMapping("insertProcess")
    @ResponseBody
    public R   insertProcess(@RequestBody PurchaseProcessEntity purchaseProcessEntity){
        try {
            int num = purchaseService.insertProcess(purchaseProcessEntity);
            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }

    }

    /**
     * 根据采购订单号查询审批信息
     * @param
     * @return
     */
    @RequestMapping("getProcessBySPR")
    @ResponseBody
   public R   getProcessBySPR(){
       try {
           UserEntity user=(UserEntity) this.getBean("user");
           List<PurchaseProcessEntity> processBySPR = purchaseService.getProcessBySPR(user.getCode());
           /*List<String> list=new ArrayList<>();
           list.add(purchaseids);
           List<PurchaseProcessEntity> processList = purchaseService.getProcessList(list);*/
         /* PurchaseProcessEntity purchaseProcessEntity=new PurchaseProcessEntity();
           purchaseProcessEntity.setPurchaseNo("2");
           purchaseProcessEntity.setSpr("2");
           purchaseProcessEntity.setSTATUS("2");
           purchaseProcessEntity.setTjr("2");
           List<PurchaseProcessEntity> list=new ArrayList<>();
           list.add(purchaseProcessEntity);*/
           /*int num = purchaseService.insertProcess(purchaseProcessEntity);*/
           return R.build(processBySPR);
       }catch (Exception e){
           e.printStackTrace();
           return R.buildError(ResultStatusEnum.ERROR);
       }

   }



    /**
     * 获取已审批的，供应商类型为‘’合作类型‘’的供应商
     * @return
     */
    @RequestMapping("getFilterCustomer2List")
    @ResponseBody
    public R getFilterCustomer2List(){
        try {
            List<SelectVo> allList = customerService.getFilterCustomer2List();
            return R.build(allList);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }

    }


    /**
     * 补货采购订单--分页
     */
    @GetMapping(value = "purchaseOrderRestockByPage")
    @ResponseBody
    public R purchaseOrderRestockByPage(PurchaseOrderRestockReq req) {
        try {
            LOGGER.info("出口业务-采购-补货采购订单--分页");
            PageInfo<PurchaseOrderRestockRes> pageInfo = purchaseAllService.purchaseOrderRestockByPage(req);
            return R.build(0, "", pageInfo.getTotal(), pageInfo.getList());
        } catch (Exception e) {
            LOGGER.info("出口业务-采购-补货采购订单--分页异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }
    /**
     * 补货采购订单--导出
     * @return
     */
    @RequestMapping("purchaseOrderRestockExport")
    @ResponseBody
    public R purchaseOrderRestockExport(PurchaseOrderRestockReq req){
        try {
            LOGGER.info("出口业务-采购-补货采购订单--导出");
            JSONObject info = purchaseAllService.purchaseOrderRestockExport(req);
            return R.build(info);
        } catch (Exception e) {
            LOGGER.info("出口业务-采购-补货采购订单--导出异常:" + e);
            return R.build(ResultStatusEnum.ERROR);
        }
    }



    /**
     * 采购产品整合--分页
     */
    @GetMapping(value = "purchaseProductIntegrationByPage")
    @ResponseBody
    public R purchaseProductIntegrationByPage(PurchaseProductIntegrationReq req) {
        try {
            LOGGER.info("出口业务-采购-采购产品整合--分页");
            PageInfo<PurchaseProductIntegrationRes> pageInfo = purchaseAllService.purchaseProductIntegrationByPage(req);
            return R.build(0, "", pageInfo.getTotal(), pageInfo.getList());
        } catch (Exception e) {
            LOGGER.info("出口业务-采购-采购产品整合--分页异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }
    /**
     * 采购产品整合--导出
     * @return
     */
    @RequestMapping("purchaseProductIntegrationExport")
    @ResponseBody
    public R purchaseProductIntegrationExport(PurchaseProductIntegrationReq req){
        try {
            LOGGER.info("出口业务-采购-采购产品整合--导出");
            JSONObject info = purchaseAllService.purchaseProductIntegrationExport(req);
            return R.build(info);
        } catch (Exception e) {
            LOGGER.info("出口业务-采购-采购产品整合--导出异常:" + e);
            return R.build(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 获取采购信息
     * @param purchaseNo 采购单号
     * @return 采购信息
     */
    @GetMapping("getPurchaseInfo")
    @ResponseBody
    public R getPurchaseInfo(String purchaseNo){
        try {
            LOGGER.info("出口业务-采购-获取采购信息");
            Purchase purchase = new Purchase();
            purchase.setPurchaseOrderNo(purchaseNo);
            Purchase purchaseInfo = purchaseService.getPurchaseInfo(purchase);
            return R.build(purchaseInfo);
        } catch (Exception e) {
            LOGGER.info("出口业务-采购-获取采购信息异常:" + e);
            return R.build(ResultStatusEnum.ERROR);
        }

    }



    /**
     * 样品采购付款详情--分页
     */
    @GetMapping(value = "purchaseSampleStatisticsByPage")
    @ResponseBody
    public R purchaseSampleStatisticsByPage(purchaseSampleStatisticsReq req) {
        try {
            LOGGER.info("出口业务-采购-样品采购付款详情--分页");
            PageInfo<purchaseSampleStatisticsRes> pageInfo = purchaseAllService.purchaseSampleStatisticsByPage(req);
            return R.build(0, "", pageInfo.getTotal(), pageInfo.getList());
        } catch (Exception e) {
            LOGGER.info("出口业务-采购-样品采购付款详情--分页异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }
    /**
     * 样品采购付款详情--导出
     * @return
     */
    @RequestMapping("purchaseSampleStatisticsExport")
    @ResponseBody
    public R purchaseSampleStatisticsExport(purchaseSampleStatisticsReq req){
        try {
            LOGGER.info("出口业务-采购-样品采购付款详情--导出");
            JSONObject info = purchaseAllService.purchaseSampleStatisticsExport(req);
            return R.build(info);
        } catch (Exception e) {
            LOGGER.info("出口业务-采购-样品采购付款详情--导出异常:" + e);
            return R.build(ResultStatusEnum.ERROR);
        }
    }

}
